<template>
  <div>
    <v-dialog title="选择合同" :show.sync="dialogVisible" class="dialogForm" width="1200px" @beforeClose="beforeClose" :close-on-click-modal="false">
      <div class="card-title">子合同信息</div>
      <el-form ref="projectForm" :model="projectForm" class="form-wrap" size="small" :rules="projectForm_rules" label-position="top">
        <el-form-item label="合同编号" prop="contractNum">
          <el-input v-halfCharCode v-model="projectForm.contractNum" maxlength="50" placeholder="请输入合同编号" />
        </el-form-item>
        <el-form-item label="合同类型" prop="contractType">
          <el-select clearable v-model="projectForm.contractType" placeholder="请选择合同类型">
            <el-option v-for="item in contractTypes" :key="item.label" :label="item.label" :value="item.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="合同金额(元)" prop="contractAmount">
          <el-input v-halfCharCode v-model="projectForm.contractAmount" maxlength="18" placeholder="请输入合同金额" />
        </el-form-item>
        <el-form-item label="单价(元/m²)" prop="unitPrice">
          <el-input v-halfCharCode v-model="projectForm.unitPrice" maxlength="18" placeholder="请输入单价" />
        </el-form-item>
        <el-form-item label="签订日期" prop="contractDate">
          <el-date-picker v-model="projectForm.contractDate" type="date" value-format="yyyy-MM-dd" format="yyyy-MM-dd" placeholder="请选择签订日期"></el-date-picker>
        </el-form-item>
        <el-form-item label="合同开始日期" prop="startDate">
          <el-date-picker v-model="projectForm.startDate" type="date" value-format="yyyy-MM-dd" format="yyyy-MM-dd" placeholder="请选择合同开始日期" @change="handleChooseStartDate"></el-date-picker>
        </el-form-item>
        <el-form-item label="合同结束日期" prop="endDate">
          <el-date-picker v-model="projectForm.endDate" type="date" value-format="yyyy-MM-dd" format="yyyy-MM-dd" placeholder="请选择合同结束日期" @change="handleChooseEndDate"></el-date-picker>
        </el-form-item>
        <el-form-item label="乙方单位名称" prop="partybUnit">
          <el-input v-halfCharCode v-model="projectForm.partybUnit" maxlength="100" placeholder="请输入乙方单位名称" />
        </el-form-item>
        <el-form-item label="联系人" prop="partybContact">
          <el-input v-halfCharCode v-model="projectForm.partybContact" maxlength="50" placeholder="请输入联系人" />
        </el-form-item>
        <el-form-item label="联系电话" prop="partybPhone">
          <el-input v-halfCharCode v-model="projectForm.partybPhone" maxlength="100" placeholder="请输入联系电话" />
        </el-form-item>
        <el-form-item label="是否有补充协议" prop="supplement">
          <el-select clearable v-model="projectForm.supplement" placeholder="请选择合同类型">
            <el-option v-for="item in supplements" :key="item.label" :label="item.label" :value="item.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="补充协议签订日期" prop="signDate" v-if="projectForm.supplement === '1'">
          <el-date-picker v-model="projectForm.signDate" type="date" value-format="yyyy-MM-dd" format="yyyy-MM-dd" placeholder="请选择合同结束日期"></el-date-picker>
        </el-form-item>
        <el-form-item label="补充协议期限" prop="suppleStart" v-if="projectForm.supplement === '1'">
          <el-date-picker type="daterange" start-placeholder="开始日期" end-placeholder="结束日期" v-model="projectForm.suppleStart" format="yyyy-MM-dd" valueFormat="yyyy-MM-dd"></el-date-picker>
        </el-form-item>
        <el-form-item label="补充协议金额(元)" prop="suppleAmount" v-if="projectForm.supplement === '1'">
          <el-input v-halfCharCode v-model="projectForm.suppleAmount" maxlength="18" placeholder="请输入补充协议金额" />
        </el-form-item>
      </el-form>
      <div class="handling-opinions" style="padding:10px 0 0;">
        <div class="other-fee">
          <span>其他费用</span>
          <el-button type="primary" size="mini" @click="handleClickAdd">添加</el-button>
        </div>
        <el-table :data="projectForm.otherExpenses" align="left">
          <el-table-column prop="expensesName" label="费用项目名称" width="120">
            <template slot-scope="scope">
              <el-input v-halfCharCode v-model="scope.row.expensesName" maxlength="100" v-if="isAdd || scope.row.newAdd" />
              <span v-else>{{scope.row.expensesName}}</span>
            </template>
          </el-table-column>
          <el-table-column prop="amount" label="金额（元）" width="120">
            <template slot-scope="scope">
              <el-input v-halfCharCode v-model="scope.row.amount" maxlength="18" v-if="isAdd || scope.row.newAdd" @blur="changeOtherAmount(scope.row.amount,scope.$index)" />
              <span v-else>{{scope.row.amount}}</span>
            </template>
          </el-table-column>
          <el-table-column prop="remarks" label="备注" width="120">
            <template slot-scope="scope">
              <el-input v-halfCharCode v-model="scope.row.remarks" maxlength="200" v-if="isAdd || scope.row.newAdd" />
              <span v-else>{{scope.row.remarks}}</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="60">
            <template slot-scope="scope">
              <el-button v-if="!isAdd" @click.native.prevent="handleClickEdit(scope.row)" type="text" size="small">编辑</el-button>
              <el-button type="text" size="small" @click.native.prevent="handleClickDelete(scope.$index,otherExpenses)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <el-form ref="remarksForm" :model="remarksForm" class="form-wrap" size="small" label-position="top">
        <el-form-item label="备注" class="full" prop="remarks">
          <el-input v-halfCharCode v-model="remarksForm.remarks" maxlength="200" placeholder="请输入" />
        </el-form-item>
      </el-form>
      <div v-if="projectForm.supplement === '1'">
        <div class="card-title">补充协议</div>
        <div class="handling-opinions">
          <v-upload
            ref="otherUpload"
            :busId="projectForm.projectSubContractId"
            modelType="otherSupplements"
            @onSuccess="otherSuccess"
            @loadCompleted="otherLoadCompleted"
            isShowFileList
            :isView="false"
            multiple
            v-model="otherFileList"
          />
        </div>
      </div>
      <div class="card-title">附件</div>
      <div class="handling-opinions">
        <v-upload
          ref="fileUpload"
          :busId="projectForm.projectSubContractId"
          modelType="supplements"
          @onSuccess="onSuccess"
          @loadCompleted="loadCompleted"
          isShowFileList
          :isView="false"
          multiple
          v-model="fileList"
        />
      </div>
      <span slot="foot">
        <el-button size="small" class="dialog-button-right" @click="handleDialogClear">取消</el-button>
        <el-button size="small" class="dialog-button-left" type="primary" @click="submitForm">保存</el-button>
      </span>
    </v-dialog>
  </div>
</template>

<script>
import { validateCode } from '../api/contract'
import { doubleValidate, validatePhone } from '~/utils/validate.js'
export default {
  name: "sub-contract",
  created () {
    this.contractTypes = this.getDict('epc_contract_type')
  },
  data () {
    let validateContractNum = (rule, value, callback) => {
      if (!value) {
        callback()
      }
      this.validateCodeOnly(value, callback)
    };
    return {
      dialogVisible: false,
      isAdd: true,
      projectForm: {
        projectId: '',
        projectTenderId: '',
        projectSubContractId: '',
        projectName: '',
        projectAddress: '',
        projectType: '',
        projectContractId: '',
        contractNum: '',
        contractType: '',
        contractAmount: '',
        unitPrice: '',
        contractDate: '',
        startDate: '',
        endDate: '',
        partybUnit: '',
        partybContact: '',
        partybPhone: '',
        supplement: '',
        signDate: '',
        suppleStart: '',
        suppleEnd: '',
        suppleAmount: '',
        remarks: '',
        otherExpenses: []
      },
      remarksForm: {
        remarks: '',
      },
      otherFileList: [],
      fileList: [],
      contractTypes: [],
      supplements: [
        {
          value: '1',
          label: '是'
        },
        {
          value: '0',
          label: '否'
        }
      ],
      projectForm_rules: {
        contractNum: [{ required: true, message: '请输入合同编号', trigger: 'blur' },
        { validator: validateContractNum, trigger: "blur" }],
        contractType: [{ required: true, message: '请选择合同类型', trigger: 'change' }],
        contractAmount: [{ required: true, message: '请输入合同金额', trigger: 'blur' },
        { validator: doubleValidate, trigger: "blur" }],
        unitPrice: [{ required: false, message: '请输入单价', trigger: 'blur' },
        { validator: doubleValidate, trigger: "blur" }],
        contractDate: [{ required: true, message: '请选择签订日期', trigger: 'blur' }],
        startDate: [{ required: true, message: '请选择合同开始日期', trigger: 'blur' }],
        endDate: [{ required: true, message: '请选择合同结束日期', trigger: 'blur' }],
        partybUnit: [{ required: true, message: '请输入乙方单位名称', trigger: 'blur' }],
        partybContact: [{ required: true, message: '请输入联系人', trigger: 'blur' }],
        partybPhone: [{ required: true, message: '请输入联系电话', trigger: 'blur' },
        { validator: validatePhone, trigger: "blur" }],
        supplement: [{ required: true, message: '请选择是否有补充协议', trigger: 'change' }],
        signDate: [{ required: true, message: '请选择补充协议签订日期', trigger: 'blur' }],
        suppleStart: [{ required: true, message: '请选择补充协议期限', trigger: 'blur' }],
        suppleAmount: [{ required: true, message: '请输入补充协议金额', trigger: 'blur' },
        { validator: doubleValidate, trigger: "blur" }],
      }
    }
  },
  methods: {
    //打开弹框
    showDialog (item) {
      this.dialogVisible = true
      if (item) {
        this.projectForm = item.row
        this.isAdd = false
        this.projectForm.otherExpenses.map(it => {
          it.newAdd = false
        })
        this.remarksForm.remarks = this.projectForm.remarks
        this.projectForm.suppleStart = this.projectForm.suppleStart && this.projectForm.suppleEnd ? [this.projectForm.suppleStart, this.projectForm.suppleEnd] : []
      }
    },
    //关闭弹框
    beforeClose (done) {
      this.projectForm.remarks = this.remarksForm.remarks
      this.projectForm.suppleEnd = this.projectForm.suppleStart[1]
      this.projectForm.suppleStart = this.projectForm.suppleStart[0]
      this.$emit('beforeClose')
    },
    //取消
    handleDialogClear () {
      this.projectForm.remarks = this.remarksForm.remarks
      this.projectForm.suppleEnd = this.projectForm.suppleStart[1]
      this.projectForm.suppleStart = this.projectForm.suppleStart[0]
      this.$emit('handleClose')
      this.dialogVisible = false
    },
    //其他费用信息新增
    handleClickAdd () {
      this.projectForm.otherExpenses.push({
        expensesName: '',
        amount: '',
        remarks: '',
        newAdd: true
      })
    },
    //其他费用信息编辑
    handleClickEdit (row) {
      this.$set(row, 'newAdd', true)
      this.isAdd = true
      this.$nextTick(() => {
        this.isAdd = false
      })
    },
    //其他费用信息删除
    handleClickDelete (index, rows) {
      rows.splice(index, 1)
    },
    //保存
    submitForm () {
      this.$refs.projectForm.validate(valid => {
        if (valid) {
          if (this.projectForm.supplement === '1') {
            if (this.otherFileList.length > 0 || this.$refs.otherUpload.loadFileList.length > 0) {
              this.$refs.otherUpload.submit()
            } else {
              this.$message.warning('请上传补充协议附件！')
            }
          } else {
            this.$refs.fileUpload.submit()
          }
        }
      })
    },
    handleDialogClick () {
      this.projectForm.remarks = this.remarksForm.remarks
      this.projectForm.suppleEnd = this.projectForm.suppleStart[1]
      this.projectForm.suppleStart = this.projectForm.suppleStart[0]
      this.$emit('handleDialogsSave', { 'arr': this.projectForm })
      this.dialogVisible = false
    },
    //补充协议文件上传
    otherSuccess (response, file, fileList) {
      //文件上传成功，开始保存表单
      if (fileList !== undefined && fileList.length > 0) {
        if (response.data) {
          this.projectForm.projectSubContractId = response.data
          this.$refs.fileUpload.submit('supplements', this.projectForm.projectSubContractId)
        } else {
          this.err('文件上传失败')
        }
      } else {
        this.$refs.fileUpload.submit()
      }
    },
    //文件上传
    onSuccess (response, file, fileList) {
      //文件上传成功，开始保存表单
      if (fileList !== undefined && fileList.length > 0) {
        if (response.data) {
          this.handleDialogClick()
        } else {
          this.err('文件上传失败')
        }
      } else {
        this.handleDialogClick()
      }
    },
    //合同开始结束日期校验
    handleChooseStartDate () {
      if (new Date(this.projectForm.startDate) > new Date(this.projectForm.endDate)) {
        this.$message.error('合同开始日期不能晚于合同结束日期')
        this.projectForm.startDate = ''
      }
    },
    handleChooseEndDate () {
      if (new Date(this.projectForm.startDate) > new Date(this.projectForm.endDate)) {
        this.$message.error('合同结束日期不能早于合同开始日期')
        this.projectForm.endDate = ''
      }
    },
    //补充协议附件回显过滤
    otherLoadCompleted (data) {
      this.$refs.otherUpload.loadFileList = data.filter(item => item.module === 'otherSupplements')
    },
    //附件回显过滤
    loadCompleted (data) {
      this.$refs.fileUpload.loadFileList = data.filter(item => item.module === 'supplements')
    },
    //验证合同编号是否存在
    validateCodeOnly (value, callback) {
      validateCode({ "vType": '2', "code": value, 'id': this.projectForm.projectSubContractId }).then(rep => {
        let vr = rep.data.data
        if (vr === 0) {
          return callback();
        } else {
          return callback(new Error("合同编号不能重复"));
        }
      })
    },
    //其他费用金额失焦校验
    changeOtherAmount (val, index) {
      if (!val) {
      } else {
        let reg = /^(([1-9]\d*)|(0))(\.\d{1,2})?$/;
        if (!reg.test(val)) {
          this.$message.error('数值格式错误（最多保留两位小数）')
          this.projectForm.otherExpenses[index].amount = ''
        } else {
          if (val > 99999999999) {
            this.$message.error('最大值不超过99999999999')
            this.projectForm.otherExpenses[index].amount = ''
          }
        }
      }
    }
  }
}
</script>

<style scoped lang='scss'>
.handling-opinions {
  padding: 20px;
  .other-fee {
    display: flex;
    justify-content: space-between;
  }
}
</style>
